<?php 
/**
 * $ModDesc
 * 
 * @version		$Id: helper.php $Revision
 * @package		modules
 * @subpackage	$Subpackage.
 * @copyright	Copyright (C) Octorber 2010 LandOfCoder.com <@emai:landofcoder@gmail.com>.All rights reserved.
 * @license		GNU General Public License version 2
 */
// no direct access
defined('_JEXEC') or die;

require_once JPATH_SITE.DS.'components'.DS.'com_content'.DS.'helpers'.DS.'route.php';
if( !defined('PhpThumbFactoryLoaded') ) {
	require_once dirname(__FILE__).DS.'libs'.DS.'phpthumb/ThumbLib.inc.php';
	define('PhpThumbFactoryLoaded',1);
}
require_once JPATH_SITE.'/components/com_content/helpers/route.php';
JModel::addIncludePath(JPATH_SITE.'/components/com_content/models');
require_once JPATH_SITE.DS.'components'.DS.'com_content'.DS.'helpers'.DS.'route.php';
abstract class modLofContentNews {
	/**
	 * @var static string $regex;
	 */
	static $regex = "#<img.+src\s*=\s*\"([^\"]*)\"[^\>]*\>#iU";	
	
	/**
   * @var static $AID;
   */
  static $AID = '';
  static $THUMB_PATH;
  static $THUMB_URI;
  static $ISTRIPED_HTML = false;
  
  	public static function setPath( $module, $params ){
		$tmppath = JPATH_SITE.DS.'cache';//.'lofthumbs';
		$moduleName = 'lofthumbs' ;
		$thumbPath = $tmppath.DS. $moduleName.DS;
		
		if( !file_exists($tmppath) ) {
			JFolder::create( $tmppath, 0777 );
		}; 
		if( !file_exists($thumbPath) ) {
			JFolder::create( $thumbPath, 0777 );
		}; 

		self::$THUMB_PATH = $thumbPath;
		self::$THUMB_URI = JURI::base(). "cache/".$moduleName."/";
		self::$ISTRIPED_HTML = $params->get( "auto_strip_tags", 0 );
 
	}
	/**
	 * get list of articles
	 */
	public static function getList( $params, $categories, $totalItems=0 ){
		return self::_getList( $params, $categories, $totalItems=0 );	
	}
	
	/**
	 * get section information by ID
	 */
	public static function  getCategoryById( $id ){
		// Lets get the information for the current section
		$db = &JFactory::getDBO();
		$query = 'SELECT s.title, s.id, s.alias,s.path  FROM #__categories AS s' .
				' WHERE s.id = '. (int) $id;
		$db->setQuery($query, 0, 1);
		return $db->loadObject();			
	}
	
	/**
	 * get Category information by ID
	 */
	public static function  getCategoryInfo( $id ){
		// Lets get the information for the current category
		$db = &JFactory::getDBO();
		$query = 'SELECT c.*, s.id as sectionid, s.title as sectiontitle,' .
				' CASE WHEN CHAR_LENGTH(c.alias) THEN CONCAT_WS(":", c.id, c.alias) ELSE c.id END as slug'.
				' FROM #__categories AS c' .
				' INNER JOIN #__sections AS s ON s.id = c.section' .
				' WHERE c.id = '. (int) $id;
		$db->setQuery($query, 0, 1);
		return $db->loadObject();			
	}
	
	/**
	 * get list of subcategories by id
	 */
	public static function getListCategories( $idds ){
		$ids = implode(",", $idds);

		$db = &JFactory::getDBO();				
		$query = 'SELECT id, alias, path, title, parent_id' .
				' FROM #__categories AS c' .
				' WHERE c.parent_id IN ('.$ids.')';
		$db->setQuery( $query );
		$data = $db->loadObjectList();	

//		$ids = array($id);
		$output = array();
		if( $data ){
			foreach( $data as $item ){
				if( !isset($output['category'.$item->parent_id]) ){
					$output['category'.$item->parent_id] = array();
				}
				array_push( $output['category'.$item->parent_id], $item);
				$output['category'.$item->parent_id]['ids'][] = $item->id;
			}
		}
		return $output;
	}		
	
	/**
	 * get the list of k2 items
	 * 
	 * @param JParameter $params;
	 * @return Array
	 */
	public static function _getList( $params, $categories, $totalItems ){
		global $mainframe;
		$formatter           = $params->get( 'style_displaying', 'title' );
		$titleMaxChars       = $params->get( 'title_max_chars', '100' );
		$descriptionMaxChars = $params->get( 'description_max_chars', 100 );
		$thumbWidth    = (int)$params->get( 'thumbnail_width', 60 );
		$thumbHeight   = (int)$params->get( 'thumbnail_height', 60 );
		$imageHeight   = (int)$params->get( 'main_height', 300 ) ;
		$imageWidth    = (int)$params->get( 'main_width', 650 ) ;
		$isThumb       = $params->get( 'auto_renderthumb',1);
		$ordering      = $params->get('ordering', 'created-asc');
		$replacer      = $params->get('replacer','...'); 
		$limitDescriptionBy = $params->get('limit_description_by','char');
		// Get the dbo
		$db = JFactory::getDbo();
	
		// Get an instance of the generic articles model
		$model = JModel::getInstance('Articles', 'ContentModel', array('ignore_request' => true));
	
		// Set application parameters in model
		$app = JFactory::getApplication();
		$appParams = $app->getParams();
		$model->setState('params', $appParams);
	
		// Set the filters based on the module params
		$model->setState('list.start', 0);
		$model->setState('list.limit', (int) $totalItems);
		$model->setState('filter.published', 1);
	
		// Access filter
		$access = !JComponentHelper::getParams('com_content')->get('show_noauth');
		$authorised = JAccess::getAuthorisedViewLevels(JFactory::getUser()->get('id'));
		self::$AID  = $authorised;
		$model->setState('filter.access', $access);
	   

		$model->setState('filter.category_id', $categories );
	
		// User filter
		$userId = JFactory::getUser()->get('id');
		switch ($params->get('user_id') ) {
		  case 'by_me':
			$model->setState('filter.author_id', (int) $userId);
			break;
		  case 'not_me':
			$model->setState('filter.author_id', $userId);
			$model->setState('filter.author_id.include', false);
			break;
	
		  case 0:
			break;
	
		  default:
			$model->setState('filter.author_id', (int) $params->get('user_id'));
			break;
		}
	
		// Filter by language
		$model->setState('filter.language',$app->getLanguageFilter());
		//  Featured switch
		switch ( $params->get('show_featured') )  {
		  case 1:
			$model->setState('filter.featured', 'only');
			break;
		  case 0:
			$model->setState('filter.featured', 'hide');
			break;
		  default:
			$model->setState('filter.featured', 'show');
			break;
		}
	
		// Set ordering
		$ordering = preg_split( '/-/', $ordering );
		if( trim($ordering[0]) == 'rand' ){
			$model->setState('list.ordering', ' RAND() '); 
		}
		else {
		  $model->setState('list.ordering', $ordering[0]);
		  $model->setState('list.direction', $ordering[1]);
		} 
	  
		$items = $model->getItems();
		return $items;
	}
		
	
	/**
	 * get Icon's Class.
	 */
	public static  function getIcon( $item ){		
		if( $item->featured ){return 'lof-icon-featured';}
		if( time()-strtotime($item->created) < 24 * 3600 ){  return 'lof-icon-news';}
		if( time()-strtotime($item->modified) < 24 * 3600 ){  return 'lof-icon-updated';}
		return '';
	}			
	
	/**
	 * parser a custom tag in the content of article to get the image setting.
	 * 
	 * @param string $text
	 * @return array if maching.
	 */
	public static function parserCustomTag( $text ){ 
		if( preg_match("#{loftag(.*)}#s", $text, $matches, PREG_OFFSET_CAPTURE) ){ 
			return $matches;
		}	
		return null;
	}
	
	 /**
		 *  check the folder is existed, if not make a directory and set permission is 755
		 *
		 * @param array $path
		 * @access public,
		 * @return boolean.
		 */
		public function renderThumb( $path, $width=100, $height=100, $title='', $isThumb=true ){
	
			$path = str_replace( JURI::base(), '', $path );
			$imagSource = JPATH_SITE.DS. str_replace( '/', DS,  $path );
			if( file_exists($imagSource)  ) {
				if(!$isThumb){ return 	JURI::base().$path;  }
				$tmp = explode("/", $path);
				$imageName = $width."x".$height."-".$tmp[count($tmp)-1];
				$thumbPath = self::$THUMB_PATH.$imageName;
				if( !file_exists($thumbPath) ) {	
					$thumb = PhpThumbFactory::create( $imagSource  );  		
					$thumb->adaptiveResize( $width, $height);
					$thumb->save( $thumbPath  ); 
				} 
				$path = self::$THUMB_URI.$imageName;
			} 
			return $path;
		}

	/**
	 * parser a image in the content of article.
	 *
	 * @param poiter $row .
	 * @return void
	 */
	public static function lookUpImages( $row ){
		$row->images = json_decode( $row->images );
		if( isset($row->images->image_fulltext) && isset($row->images->image_intro) ){
			$row->thumbnail = $row->images->image_intro;
			$row->mainImage = $row->images->image_fulltext;	
			if( empty($row->images->image_fulltext) ){
				$row->mainImage = $row->images->image_intro;
			} 
			if( empty($row->images->image_intro) ){
				$row->thumbnail = $row->images->image_fulltext;	
			}
		}
		if( empty($row->thumbnail) && empty($row->mainImage) ){
			$text =  $row->introtext;
			$regex = "/\<img.+src\s*=\s*\"([^\"]*)\"[^\>]*\>/";
			preg_match ($regex, $text, $matches); 
			$images = (count($matches)) ? $matches : array();
			if (count($images)){
				$row->mainImage = $images[1];
				$row->thumbnail = $images[1];
			} else {
				$row->thumbnail = '';
				$row->mainImage = '';	
			}
		}
		return $row;
	}
	
	/**
	 * get image tag.
	 */
	public function getImage( $item, $imageWidth, $imageHeight, $isThumb=true ){
		$item = self::lookUpImages( $item );
		
		if( $item->mainImage ){
			$path =  self::renderThumb( $item->mainImage, $imageWidth, $imageHeight, $item->title, $isThumb );
			return '<img src="'.$path.'" title="'.$item->title.'" width="'.$imageWidth.'" alt="'.$item->title.'" />';
		}
	}
	
	/**
	 * call back function for processing data before render
	 */
	public static function onBeforeRender( $item,  $descriptionMaxChars=100, $limitDescriptionBy='char', $isAuthor=false ){
   
  		global $mainframe; 
		
		$item->slug = $item->id.':'.$item->alias;
		$item->catslug = $item->catid ? $item->catid .':'.$item->category_alias : $item->catid;
			
   		$item->text = $item->introtext;
		
		$item->introtext = JHtml::_('content.prepare', $item->introtext);
    	$item->introtext = $item->text;	  	
		$item->categoryname = $item->category_title;
		if($item->access <= self::$AID ) {
			$item->link = JRoute::_(ContentHelperRoute::getArticleRoute($item->slug, $item->catslug));
		} else {
			$item->link = JRoute::_('index.php?option=com_user&view=login');
		}
		$item->date = JHtml::_('date', $item->created, JText::_('DATE_FORMAT_LC3')); 
		$introtext 		   = preg_replace(self::$regex,"",$item->introtext);
		if( $limitDescriptionBy=='word' ){
		
			$string 		   = preg_replace( "/\s+/", " ", strip_tags($introtext) );
			$tmp 			   = explode(" ", $string);
			$item->description = $descriptionMaxChars>count($tmp)?$string:implode(" ",array_slice($tmp, 0, $descriptionMaxChars));
		} else {
			$item->description = self::substring( $introtext , $descriptionMaxChars, '', self::$ISTRIPED_HTML );	

		}
		$item->rating =  0;
		$item->categoryLink = urldecode(JRoute::_(ContentHelperRoute::getCategoryRoute($item->catid)));
		if( $isAuthor ){
			if (! empty($item->created_by_alias)) {
				$item->author = $item->created_by_alias;
			} else {
				$author = &JFactory::getUser($item->created_by);
				$item->author = $author->name;
			}
		}
		return $item;
	}
	
	/**
	 * Load Modules Joomla By position's name
	 */
	public static function loadModulesByPosition( $position='' ){
		$modules = JModuleHelper::getModules( $position );
		if( $modules ) {
			$document = &JFactory::getDocument();
			$renderer = $document->loadRenderer('module');
			$output='';
			foreach( $modules  as $module ){
				$output .= '<div class="lof-module">'.$renderer->render( $module, array('style' => 'raw') ).'</div>';
			}
			return $output;
		}
		return ;
	}
  
	/**
	 * load css - javascript file.
	 * 
	 * @param JParameter $params;
	 * @param JModule $module
	 * @return void.
	 */
	public static function loadMediaFiles( $params, $module, $theme='' ){
		global $mainframe;
		$document = &JFactory::getDocument();
		$app = JFactory::getApplication();
		$template = $app->getTemplate();		
		if( $theme && $theme != -1 ){
			$tPath = JPATH_BASE.DS.'templates'.DS.$template.DS.'css'.DS.$module->module.'_'.$theme.'.css';
			if( file_exists($tPath) ){
				JHTML::stylesheet( $module->module.'_'.$theme.'.css','templates/'.$mainframe->getTemplate().'/css/');
			} else {
				$document->addStyleSheet( JURI::root(true). '/modules/'.$module->module.'/tmpl/'.$theme.'/assets/style.css' );	
			}
		} else { 
			$document->addStyleSheet( JURI::root(true). '/modules/'.$module->module.'/assets/style.css' );	
		}
	}
	
	/**
	 * get a subtring with the max length setting.
	 * 
	 * @param string $text;
	 * @param int $length limit characters showing;
	 * @param string $replacer;
	 * @return tring;
	 */
	public static function substring( $text, $length = 100, $replacer='...', $isStriped=true ){
		$string = $isStriped ? strip_tags( $text ) : $text;

		return JString::strlen( $string ) > $length ?  JHtml::_('string.truncate', $string, $length ): $string;
	}
}
?>